package com.xnyzc.lhy.task.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xnyzc.lhy.common.component.config.security.RocketConfig;
import com.xnyzc.lhy.common.component.sms.AliCloudSMSUtils;
import com.xnyzc.lhy.common.constant.AliCloudSmsConstant;
import com.xnyzc.lhy.common.constant.MqConstant;
import com.xnyzc.lhy.common.constant.MqConsumerGroupConstant;
import com.xnyzc.lhy.common.penum.cms.EVehicleType;
import com.xnyzc.lhy.common.penum.vehicle.ECallVehType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.mis.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.mis.entity.system.OaSysSendMessage;
import com.xnyzc.lhy.order.entity.user.OaDUser;
import com.xnyzc.lhy.task.mapper.sys.OaDUserMapper;
import com.xnyzc.lhy.task.mapper.sys.OaSysSendMessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.List;

@Slf4j
@Component
public class MQConsumerForDriver {
    /**
     * rocketMq 配置文件
     */
    @Autowired
    RocketConfig rocketConfig;
    @Autowired
    private OaSysSendMessageMapper oaSysSendMessageMapper;
    @Autowired
    private OaDUserMapper oaDUserMapper;

    private DefaultMQPushConsumer consumer;


//    @Value("${rocketMq.isStart}")
//    private boolean isStart;

    /**
     * 开启监听
     */
    @PostConstruct
    public void init() {
        log.info(rocketConfig.getTopic() + "--------------------------------------------------" + rocketConfig.getNameServerAddr());
        try {
            consumer = new DefaultMQPushConsumer(MqConsumerGroupConstant.SEND_MESSAGE_DRIVER);
            consumer.setNamesrvAddr(rocketConfig.getNameServerAddr());
            consumer.subscribe(rocketConfig.getTopic(), MqConstant.NEW_ORDER_TO_DRIVER);
            //批量消费的最大消息条数
            consumer.setConsumeMessageBatchMaxSize(10);
            //设置消费策略:队列头消费
            consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
            /**
             *  设置监听
             */
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                    for (MessageExt msg : msgs) {
                        MQConsumerForDriver.this.dealBody(msg);
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            consumer.start();
            log.info("---------MQConsumer启动完成------------");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("---------MQConsumer初始化失败------------",e);
        }
    }

    private void dealBody(MessageExt messageExt) {
        String data = new String(messageExt.getBody());
        log.info("新订单短信发送司机，MQ消息-" + data);
        OaCOrderPersonal personal = JSON.parseObject(data, OaCOrderPersonal.class);
        String officeId = personal.getOfficeId();
        if (personal == null) {
            return;
        }
        //根据司机id查询司机电话
        OaDUser oaDUser = oaDUserMapper.selectById(personal.getDriverId());
        if (oaDUser==null || CheckUtil.objIsEmpty(oaDUser.getDriverPhone())){
            return;
        }
        QueryWrapper<OaSysSendMessage> oaSysSendMessageQueryWrapper = new QueryWrapper<>();
        oaSysSendMessageQueryWrapper.eq(OaSysSendMessage.OFFICE_ID, officeId);
        OaSysSendMessage oaSysSendMessage = oaSysSendMessageMapper.selectOne(oaSysSendMessageQueryWrapper);
        if (oaSysSendMessage == null) {
            return;
        }
        int isSendMessage = oaSysSendMessage.getNewOrderToDriver();
        if (isSendMessage == 1) {
            JSONObject json = new JSONObject();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            json.put("ordertime", sdf.format(personal.getAppointment()));
            json.put("orderId", personal.getOrderNo());
            json.put("calltype", ECallVehType.finaByType(personal.getOrderType()).getValue() );
            json.put("startpoint", personal.getStartAddress());
            json.put("endpoint", personal.getEndAddress());
            json.put("customer", personal.getPassengerName());
            json.put("phone", personal.getPassengerPhone());
            //发送短信
            AliCloudSMSUtils.sendMessage(oaDUser.getDriverPhone(), AliCloudSmsConstant.SEND_MESSAGE_TO_DRIVER, json);
            log.info("短信已发送给司机！ 电话："+oaDUser.getDriverPhone());
        }
    }
}
